package com.snailvr.tv.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.snail.readyvr.R;
import com.snail.readyvr.util.LogUtils;
import com.snail.readyvr.util.SPUtils;
import com.snail.readyvr.util.ToastUtils;
import com.snailvr.tv.Definition;
import com.snailvr.tv.ui.base.CheckPermissionsActivity;
import com.snailvr.tv.ui.view.FovDialog;
import com.snailvr.tv.ui.view.NavigationDialog;
import com.snailvr.tv.ui.view.ProjectionDialog;
import com.snailvr.tv.util.BrightnessUtil;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.snailvr.tv.Definition.KEY_FOV;
import static com.snailvr.tv.Definition.PLAY_SETTING_RESULT_CODE;


/**
 * Created by Administrator on 2016/9/30.
 */
public class SettingActivity extends CheckPermissionsActivity {

    @BindView(R.id.layout_settings)
    LinearLayout mLinearLayout;

    @BindView(R.id.seek_bar_voice)
    SeekBar mVoiceBar;

    @BindView(R.id.seek_bar_brightness)
    SeekBar mBrightBar;

    @BindView(R.id.img_view_icon2)
    ImageView mProjectionImg;

    @BindView(R.id.img_view_icon3)
    ImageView mNavigationImg;

    @BindArray(R.array.language_names)
    String[] mNames;

    private AudioManager mAudioManager;
    /**
     * 最大声音
     */
    private int mMaxVolume;
    /**
     * 当前声音
     */
    private int mVolume;
    /**
     * 当前亮度
     */
    private int mBrightness;

    private boolean permission = false;

    private static final int CODE_WRITE_SETTINGS_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isinitVariables = false;
        super.onCreate(savedInstanceState);
        checkSettingPermission();
    }

    @Override
    protected void initVariables() {
        try {
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            mMaxVolume = mAudioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            LogUtils.d("mMaxVolume-->" + mMaxVolume);
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            LogUtils.d("mVolume-->" + mVolume);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果开启了自动亮度调节，则关闭之
        if (BrightnessUtil.isAutoBrightness(this)) {
            BrightnessUtil.stopAutoBrightness(this);
        }

        mBrightness = getScreenBrightness();
        Log.i(TAG,"system screen brightness is :" + mBrightness);
        if (mVoiceBar != null) {
            mVoiceBar.setMax(mMaxVolume);
            mVoiceBar.setProgress(mVolume);
        }
        if(mBrightBar != null) {
            mBrightBar.setMax(255);
            mBrightBar.setProgress(mBrightness);
        }
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.setting_list);
        ButterKnife.bind(this);

        mLinearLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        /*if(permission) {
            mVoiceBar.setMax(mMaxVolume);
            mVoiceBar.setProgress(mVolume);
        }*/
        mVoiceBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if(!fromUser)
                    return;
                mVolume = progress;
                LogUtils.d("mVolume onProgressChanged-->" + mVolume);
                Log.i(TAG,"current Volume :" + mVolume);
                if(permission && mAudioManager != null)
                     mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        /*mBrightBar.setMax(255);
        mBrightBar.setProgress(mBrightness);*/
        mBrightBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                LogUtils.d("mBrightBar onProgressChanged-->" + progress);
                setScreenBrightness(seekBar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    @Override
    protected void loadData() {

    }

    @OnClick(R.id.layout_root)
    public void onClose() {
        setResult(PLAY_SETTING_RESULT_CODE);
        this.finish();
    }

    //设置屏幕亮度的函数
    private void setScreenBrightness(int brightness) {
        // 根据当前进度改变屏幕亮度
        if (permission)
            Settings.System.putInt(getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS, brightness);
    }

    public int getScreenBrightness() {
        int value = 0;
        ContentResolver cr = getContentResolver();
        try {
            value = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {

        }
        return value;

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            LogUtils.d("KEYCODE_VOLUME_DOWN");
            if(mVolume > 0) {
                mVolume--;
                mVoiceBar.setProgress(mVolume);
                if(permission && mAudioManager != null)
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mVolume, 0);
            }
            return  true;

        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            LogUtils.d("KEYCODE_VOLUME_UP");
            if(mVolume < mMaxVolume) {
                mVolume ++;
                mVoiceBar.setProgress(mVolume);
                if(permission && mAudioManager != null)
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mVolume, 0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void hasGetAllPermissions() {

    }

    private void checkSettingPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permission = Settings.System.canWrite(this);
        } else {
            permission = true;
        }
        if (permission) {
            initVariables();
        } else {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                ToastUtils.show(this,R.string.high_settings);
                if(Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.M)
                    ToastUtils.show(this,R.string.high_settings_tip, Toast.LENGTH_LONG);
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + this.getPackageName()));
                this.startActivityForResult(intent, CODE_WRITE_SETTINGS_PERMISSION);
            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_WRITE_SETTINGS_PERMISSION && Settings.System.canWrite(SettingActivity.this)){
            permission = true;
            initVariables();
            LogUtils.d("onActivityResult CODE_WRITE_SETTINGS_PERMISSION");
        }else {
            ToastUtils.show(this,R.string.high_settings_faile);
            finish();
        }
    }
    @Override
    public void finish() {
        this.setResult(Definition.PLAY_SETTING_RESULT_CODE);
        super.finish();
        overridePendingTransition(0,R.anim.slide_bottom_out);
    }

    @OnClick(R.id.change_language)
    public void onClickChangeLanguage(){

    }

    @OnClick(R.id.layout_button_set_angle)
    public void showPlayAngle() {
        FovDialog.Builder builder = new FovDialog.Builder(this, null);
        AlertDialog alertDialog = builder.addSubmitListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int mFov = (int) v.getTag();
                SPUtils.put(SettingActivity.this,KEY_FOV,mFov);

            }
        }).show();
    }

    @OnClick(R.id.layout_button_projection_type)
    public void showProjectionSelect() {
//        Intent intent = new Intent(this, PlayModeActivity.class);
//        startActivity(intent);

        ProjectionDialog.Builder builder = new ProjectionDialog.Builder(this);
        builder.addOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeProjectionIcon();

            }
        }).show();

    }

    @OnClick(R.id.layout_button_inductive_reset)
    public void showNavigationSelect() {
        NavigationDialog.Builder builder = new NavigationDialog.Builder(this);
        builder.addOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeNavigationIcon();
            }
        }).show();
    }

    private void changeProjectionIcon() {
        int projection = (int)SPUtils.get(this,Definition.KEY_PROJECTION,Definition.TYPE_180_3D_Left_Right);

        switch (projection) {
            case Definition.TYPE_2D:
                mProjectionImg.setImageResource(R.drawable.ic_2d);
                break;
            case Definition.TYPE_180_2D:
                mProjectionImg.setImageResource(R.drawable.ic_180_2d_overandunder);
                break;
            case Definition.TYPE_180_3D_Left_Right:
                mProjectionImg.setImageResource(R.drawable.ic_180_3d_sidebyside);
                break;
            case Definition.TYPE_180_3D_Up_Down:
                mProjectionImg.setImageResource(R.drawable.ic_180_3d_overandunder);
                break;
            case Definition.TYPE_360_2D:
                mProjectionImg.setImageResource(R.drawable.ic_360_2d);
                break;
            case Definition.TYPE_360_3D_Left_Right:
                mProjectionImg.setImageResource(R.drawable.ic_360_3d_sidebyside);
                break;
            case Definition.TYPE_360_3D_Up_Down:
                mProjectionImg.setImageResource(R.drawable.ic_360_3d_overandunder);
                break;
            default:
                mProjectionImg.setImageResource(R.drawable.ic_180_3d_sidebyside);
                break;
        }
    }


    private void changeNavigationIcon() {
        int navigaitonMode = (int)SPUtils.get(this,Definition.KEY_SNVR_NAVIGATION,Definition.SNVR_NAVIGATION_SENSOR);
        switch (navigaitonMode) {
            case Definition.SNVR_NAVIGATION_SENSOR:
                mNavigationImg.setImageResource(R.drawable.automatic);
                break;
            case Definition.SNVR_NAVIGATION_TOUCH:
                mNavigationImg.setImageResource(R.drawable.manual);
                break;
            case Definition.SNVR_NAVIGATION_BOTH:
                mNavigationImg.setImageResource(R.drawable.both);
                break;
            default:
                mNavigationImg.setImageResource(R.drawable.automatic);
                break;
        }
    }

}
